package com.heima.app.gateway.filter;

import com.heima.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.function.Consumer;

@Component
@Slf4j
public class AuthFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2.得到对象中的token
        String token = request.getHeaders().getFirst("token");

        //3.校验当前路径是不是登录接口
        if (request.getPath().toString().contains("login")) {
            //放行
            return chain.filter(exchange);
        }

        //4.判断token是否为空
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //5.校验token有效性(JWT工具类)
        Claims claims = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claims);
        if (i == 1 || i == 2){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //1.从claims中获取token中的用户id,
        //这里使用get方法传入id得到用户id是因为AppJwtUtil类中生成token时设置的key是id,类型为Long
        Integer id = (Integer) claims.get("id");

        //2.将id设置到请求头中并刷新
        ServerHttpRequest newRequest = request.mutate().headers(new Consumer<HttpHeaders>() {
            @Override
            public void accept(HttpHeaders httpHeaders) {
                //请求对象是只读的，只能生成一个新的请求将userId写入
                httpHeaders.add("userId",id.toString());
            }
        }).build();
        //并将新的请求刷新到exchange中
        exchange.mutate().request(newRequest).build();

        //6.放行
        return chain.filter(exchange);
    }
}
